<?php

namespace App\Jobs;

use App\Engine\TokenService;
use App\Models\ShareLog;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Sys as SysModel;
use App\Models\User as UserModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ShareLogJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $uid;
    private $sysModel;
    private $userModel;
    private $shareLogModel;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($uid)
    {
        $this->uid=$uid;

    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->sysModel=new SysModel();
        $this->userModel=new UserModel();
        $this->shareLogModel=new ShareLog();
        DB::beginTransaction();
        try {
            $log=$this->shareLogModel->where("uid",$this->uid)->where("date",date("Y-m-d"))->get();
            $share_get_draw=$this->sysModel->get_Value("share_get_draw");
            $share_get_draw_limit=$this->sysModel->get_Value("share_get_draw_limit");
            if (count($log)>=$share_get_draw_limit){
                return null;
            }
            $user=UserModel::where("id",$this->uid)->first();
            if ($user){
                $user->increment("draw_times",$share_get_draw);
                $create=[
                    "uid"=>$this->uid,
                    "content"=>"分享获取抽奖次数{$share_get_draw}次",
                    "date"=>date("Y-m-d")
                ];
                $this->shareLogModel->create($create);
            }

            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            Log::error($exception->getMessage());
        }

    }
}
